import AI from "./AI";

export default class AIManger extends Laya.Script {
    // 更多参数说明请访问: https://ldc2.layabox.com/doc/?nav=zh-as-2-4-0
    owner=this.owner as Laya.Sprite
    AIPrefabArr=[]
    spawnAIArr=[]
    columnArr=[];
    player=null;
    isPlay=false;
    constructor() { super(); }
    onAwake(){
        Laya.stage.on("gamerover",this,this.gamerOver)
        Laya.stage.on("victory",this,this.gamerOver)
        Laya.stage.on("start",this,function(){this.isPlay=true})
        this.player=this.owner.parent.getChildByName("player")
        this.loadFoodPrefab();
        }
        gamerOver(){
            this.isPlay=false
            this.spawnAIArr.forEach(element => {
            element.removeSelf();
            });
            }
    loadFoodPrefab(){
        var pathArr=[
            "prefab/AI_1.json",
            ]
            var infoArr=[];
            for(var i=0;i<pathArr.length;i++){
            infoArr.push({url:pathArr[i],type:Laya.Loader.PREFAB})
            }
            Laya.loader.load(infoArr,Laya.Handler.create(this,function(result){
                for(var i=0;i<pathArr.length;i++){
                this.AIPrefabArr.push(Laya.loader.getRes(pathArr[i]))
                }
                this.ranTime=this.getRandom(300,800);
                Laya.timer.loop(this.ranTime,this,function(){
                this.spawn();
                })
                }))
                }
    spawn(){
        if(!this.isPlay)return;
        var x=this.getRandom(115,1800)
        var y=136
        var AIIndex=this.getRandom(0,this.AIPrefabArr.length-1);
        var ai=Laya.Pool.getItemByCreateFun(AIIndex.toString(),function(){
        return this.AIPrefabArr[AIIndex].create()},this);
        Laya.stage.getChildAt(0).getChildAt(0).addChild(ai);
        ai.pos(x,y);
        ai.getComponent(AI).Init(AIIndex.toString());
        this.spawnAIArr.push(ai);

    }


    getRandom(min,max){
        var value=Math.random()*(max-min);
        value=Math.round(value);
        return min+value;
        }
}